#include "rocks.h"
#include "bangdots.h"
#include "greeblies.h"
#include "random_gen.h"
#include "rockdodger_globals.h"
#include "sound.h"

struct rock_struct rock[MAX_ROCKS], *rockptr = rock;

SDL_Surface *surf_rock[NROCKS];
SDL_Surface *surf_deadrock[NROCKS];

void create_rock(float rockspeed) {
  rockptr++;
  if(rockptr - rock >= MAX_ROCKS)
    rockptr = rock;
  if(!rockptr->active && !rockptr->greeb) {
    rockptr->x = (float) xsize;
    rockptr->y = rnd() * ysize;
    rockptr->xvel = -(rockspeed) * (1 + rnd());
    rockptr->yvel = (rockspeed / 3.0) * (rnd() - 0.5);
    rockptr->type_number = random() % NROCKS;
    rockptr->heat = 0;
    rockptr->image = surf_rock[rockptr->type_number];	// [random()%NROCKS];
    rockptr->active = 1;
  }
}


void display_rocks(SDL_Surface *surf_screen) {
  int i;
  static int last_rock = 1;
  SDL_Rect dest;

  for(i = 0; i < MAX_ROCKS; i++) {
    struct rock_struct *r;
    r = &rock[i];

    if(r->active) {

      if(!r->greeb)
	last_rock = i;
      dest.w = r->image->w;
      dest.h = r->image->h;
      dest.x = (int) r->x;
      dest.y = (int) r->y;

      // Draw the rock
      SDL_BlitSurface(r->image, NULL, surf_screen, &dest);

      // Draw the heated part of the rock, in an alpha which reflects the
      // amount of heat in the rock.
      if(r->heat > 0) {
	SDL_Surface *deadrock;
	deadrock = surf_deadrock[r->type_number];
	SDL_SetAlpha(deadrock, SDL_SRCALPHA, r->heat * 255 / r->image->h);
	dest.x = (int) r->x;	// kludge
	SDL_BlitSurface(deadrock, NULL, surf_screen, &dest);
	if(rnd() < 0.3)
	  r->heat -= movementrate;
      }
      // If the rock is heated past a certain point, the water content of
      // the rock flashes to steam, releasing enough energy to destroy
      // the rock in spectacular fashion.
      if(rock[i].heat > rock[i].image->h) {
	int g;

	rock[i].active = 0;
	play_sound(1 + (int) (rnd() * 3));
	makebangdots(rock[i].x, rock[i].y, rock[i].xvel, rock[i].yvel,
		     rock[i].image, 10, 3);

	// If a greeblie was going to this rock
	if((g = rock[i].greeb)) {
	  // ...and had landed, then the greeblie explodes too.
	  if(greeb[g].landed)
	    kill_greeb(g);
	  else {
	    // If the greeblie is not yet landed, then it must now
	    // find another rock to jump to. Choose the last active
	    // rock found.
	    rock[i].greeb = 0;
	    rock[last_rock].greeb = g;
	    greeb[g].target_rock_number = last_rock;
	  }
	}
      }
    }
    // Draw any greeblies attached to (or going to) the rock, whether the rock is active or not.
    if(r->greeb && greeb[r->greeb].target_rock_number == i)
      display_greeb(&greeb[r->greeb], surf_screen);
  }
}
